axios.defaults.baseURL = getUrlData().baseURL || '/';
// http://39.96.147.43:8082
// ?baseURL=http://39.96.147.43:8082&headLicensePlateNo=鲁NF5989&timeOfStartReal=2024-11-23 19:00:00&timeOfEndReal=2024-11-23 20:00:00
new Vue({
	el: '#app',
	data() {
		return {
			timeRange: [],
			search: {
				headLicensePlateNo: '', //车牌号
				plateColor: 2, //车牌颜色
				startTime: '',
				endTime: '',
			},
			plateColors: [{
					label: '蓝色',
					value: 1
				},
				{
					label: '黄色',
					value: 2
				},
				{
					label: '黄绿色',
					value: 3
				}
			],
			loading: false,
			routeData: [],
			map: null,
			zoom: 15,
			center: [113.61827, 22.98614],
			layers: [],
			mapInfoWindow: null,
			startPanel: null,
			endPanel: null,
			palySpeed: 1,
			warningData: []
		}
	},
	created() {
		const {
			headLicensePlateNo,
			timeOfStartReal,
			timeOfEndReal,
		} = getUrlData();
		this.search.headLicensePlateNo = decodeURIComponent(headLicensePlateNo || '')
		this.search.startTime = decodeURIComponent(timeOfStartReal || '')
		this.search.endTime = decodeURIComponent(timeOfEndReal || '')
		this.timeRange = [this.search.startTime, this.search.endTime]
		if (headLicensePlateNo) {
			this.serachBtnClick()
			this.searchWarningList()
		}
	},
	mounted() {
		this.initMap()
	},
	methods: {
		initMap() {
			const source = getMapSource();
			if (source === 'tmap') {
				this.loadTmap()
			} else {
				this.loadAmap()
			}
			// 清除弹窗
			document.getElementById('map').addEventListener('click', (e) => {
				if (e.target.nodeName === "CANVAS" && this.mapInfoWindow) {
					this.mapInfoWindow.style.display = 'none';
				}
			})
		},
		loadTmap() {
			var url =
				"http://ktd.dg:20002/gateway/client-point/oauth/token?client_id=智慧水乡新城一期项目&client_secret=ZGQ5OTNkNDI2MzM0MTc0NA";
			axios({
				url: url,
				method: 'GET',
			}).then((res) => {
				const value = res.data.data
				const token = value.access_token
				const layerurl = "http://ktd.dg:18080/data-slssldt?token=" + token;
				const crs = "EPSG:4490"
				const tileMatrixLabels = "EPSG:4490_DG_BLUE_DIANZI_v4_1:"
				const zoom = this.zoom
				const _center = this.center
				let projection = new ol.proj.get(crs);
				if (crs == "EPSG:4490" || crs == "4490") {
					proj4.defs("EPSG:4490", "+proj=longlat +ellps=GRS80 +no_defs");
					projection = new ol.proj.get('EPSG:4490');
					projection.setExtent([-180, -90, 180, 90]);
				}
				var projectionExtent = projection.getExtent();
				var size = ol.extent.getWidth(projectionExtent) / 256;
				var resolutions = [];
				var matrixIds = [];
				if (crs == "EPSG:4490" || crs == "4490") {
					for (var z = 0; z < 20; ++z) {
						resolutions[z] = size / Math.pow(2, z);
						matrixIds[z] = tileMatrixLabels + z;
					}
				} else {
					for (var z = 0; z < 20; ++z) {
						resolutions[z] = size / Math.pow(2, z);
						matrixIds[z] = tileMatrixLabels + z;
					}
				}
				var origin = ol.extent.getTopLeft(projectionExtent);
				var dzdtWMTSLayer2018 = new ol.layer.Tile({
					source: new ol.source.WMTS({
						name: "东莞地图",
						url: layerurl,
						layer: "DG_BLUE_DIANZI_v4_1",
						style: '',
						matrixSet: "EPSG:4490_DG_BLUE_DIANZI_v4_1",
						format: 'image/png',
						wrapX: true,
						tileGrid: new ol.tilegrid.WMTS({
							origin: origin,
							resolutions: resolutions,
							matrixIds: matrixIds,
						}),
					}),
				});
				this.map = new ol.Map({
					layers: [
						dzdtWMTSLayer2018
					],
					target: "map",
					view: new ol.View({
						center: fmtLonLat(_center),
						projection: projection,
						zoom: zoom,
						maxZoom: 19,
						minZoom: 10,
					}),
				});
			});
		},
		loadAmap() {
			this.map = new ol.Map({
				target: 'map',
				layers: [
					new ol.layer.Tile({
						source: new ol.source.XYZ({
							url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=6',
							projection: 'EPSG:3857',
							crossOrigin: '*',
						})
					}),
					new ol.layer.Tile({
						source: new ol.source.XYZ({
							url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8',
							projection: 'EPSG:3857',
							crossOrigin: '*',
						})
					})
				],
				view: new ol.View({
					center: fmtLonLat(this.center),
					zoom: this.zoom
				})
			});
		},
		clearLayers() {
			if (!this.map) return;
			this.layers.forEach((layer) => {
				this.map.removeLayer(layer);
			});
			this.layers = [];
		},
		clearOverlays() {
			if (!this.map) return;
			var overlays = this.map.getOverlays().getArray();

			overlays.forEach((overlay) => {
				this.map.removeOverlay(overlay);
			});

			this.map.getOverlays().clear();
		},
		serachBtnClick() {
			this.loading = true;
			this.clearLayers();
			this.clearOverlays();
			this.search.headLicensePlateNo = this.search.headLicensePlateNo.trim();
			axios.post('/monitor/api/track/truckTrackQuery', this.search).then(async (res) => {
				this.loading = false;
				const trackData = res.data.obj;
				if (!trackData) {
					this.$message.warning(res.data.returnInfo);
					return;
				}

				if (!trackData.runRoute || (trackData.runRoute && trackData.runRoute.length === 0)) {
					this.$message.warning('在该时间段车辆设备不在线');
					return;
				}

				// 去重（他妈的  这一步一直没发现）
				this.routeData = removeDuplicates(trackData.runRoute);

				this.routeData.forEach(item => {
					item.lon = parseFloat(item.lon);
					item.lat = parseFloat(item.lat);
				});

				const coordinates = this.routeData.map(route => fmtLonLat([route.lon, route.lat]));

				// 画线
				drawLine(coordinates, this)

				// 画起始点
				drawPic(coordinates[0], './assets/images/start-point.png', this, this.routeData[0])
				drawPic(coordinates[coordinates.length - 1], './assets/images/end-point.png', this, this.routeData[
					coordinates.length - 1])
				// 画车
				this.drawTrack(trackData)
				// 画位置
				this.drawPos(coordinates)
			});
		},
		// 绘制点位
		drawPos(coordinates) {
			coordinates.forEach((item, index) => {
				if (index != 0 && index != coordinates.length - 1) {
					drawPos(item, './assets/images/pos.png', this, this.routeData[index])
				}
			})
		},
		palyTrackTrans() {
			const length = this.routeData?.length;
			if (!length) return
			let index = 0,
				overlay;

			const timer = setInterval(() => {
				overlay && this.map.removeOverlay(overlay);
				overlay = this.drawTrack(this.routeData[index], true);
				if (index === length - 1) {
					this.map.removeOverlay(overlay);
					clearInterval(timer)
				}
				index++
			}, 400 / this.palySpeed)
		},
		drawTrack(trackData, isPlay) {
			if (isPlay) {
				return drawPlayPic(
					fmtLonLat([trackData.lon, trackData.lat]),
					'./assets/images/car.png', this, {
						agl: trackData.agl
					})
			}

			//  画车
			if (trackData.lon) {
				let curr;
				if (trackData.gtm != void 0 || trackData.agl != void 0) {
					curr = trackData;
				} else {
					curr = this.routeData.find(item => item.lon == trackData.lon && item.lat == trackData.lat);
				}
				return drawPic(
					fmtLonLat([trackData.lon, trackData.lat]),
					'./assets/images/car.png', this, {
						adr: trackData.adr,
						gtm: curr?.gtm || '', //时间
						agl: curr?.agl
					}, true)
			} else {
				const endData = this.routeData[this.routeData.length - 1]
				return drawPic(
					fmtLonLat([endData.lon, endData.lat]),
					'./assets/images/car.png', this, {
						adr: '',
						gtm: endData.gtm, //时间
						agl: endData.agl
					}, true)
			}
		},
		timeRangeChange(value) {
			if (value) {
				this.search.startTime = formatDate(value[0]);
				this.search.endTime = formatDate(value[1]);
			} else {
				this.search.startTime = '';
				this.search.endTime = '';
			}
		},
		async searchWarningList() {
			this.loading = true;
			const {
				data
			} = await axios({
				method: 'post',
				url: '/monitor/api/warnInfo/warnInfoGpsList', // 你要请求的URL
				headers: {
					'Token': sessionStorage.getItem('token'),
					'Content-Type': 'application/json'
				}, // 你要设置的header
				data: {
					startDate: this.timeRange[0],
					endDate: this.timeRange[1],
					headLicensePlateNo: this.search.headLicensePlateNo,
					page: 1,
					pageSize: 20,
				}
			})
			if (data?.list) {
				this.warningData = data.list
			}
			this.loading = false;
		}
	}
});